package com.lagou.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.lagou.entity.CourseComment;
import com.lagou.entity.CourseCommentFavoriteRecord;
import com.lagou.service.CourseCommentService;
import mapper.CourseCommentDao;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class CourseCommentServiceImpl implements CourseCommentService {

    @Autowired
    private CourseCommentDao courseCommentDao;

    @Override
    public Integer saveComment(CourseComment comment) {

        return courseCommentDao.saveComment(comment);
    }

    @Override
    public List<CourseComment> getCommentsByCourseId(Integer courseId, Integer offset, Integer pageSize) {

        return courseCommentDao.getCommentsByCourseId(courseId, offset, pageSize);
    }

    @Override
    public Integer handlerFavorite(Integer commentId, Integer userId) {

        Integer result;
        CourseCommentFavoriteRecord favoriteRecord = courseCommentDao.existsFavorite(commentId, userId);
        if (favoriteRecord == null) {

            result = courseCommentDao.saveCommentFavorite(commentId, userId);
            if (result == 1) {

                result = courseCommentDao.updateLikeCount(1, commentId);
            }
        } else {

            int status = (Boolean) favoriteRecord.getIsDel() ? 0 : 1;
            int x = status == 0 ? 1 : -1;
            result = courseCommentDao.updateFavoriteStatus(status, commentId, userId);
            if (result == 1) {

                result = courseCommentDao.updateLikeCount(x, commentId);
            }
        }

        if (result == 0) {

            throw new RuntimeException("点赞失败");
        }

        return result;
    }
}
